<template>
  <div class="ui-zhrtc-page" :style="{ padding: closeTools ? '10px 0 0 0' : '92px 0 0 0' }">
    <div class="ui-zhrtc-toolbar-right">
      <div class="ui-button ui-zhrtc-full-btn" @click="closeTool">
        <Icon icon="ep:caret-right" />
      </div>
    </div>
    <RTCurveToolbar
      :scale="scaleSettingRef"
      @scale="onScaleChange($event)"
      :showParams="show"
      @show-params="onShowParamsChange($event)"
      @export="onExport($event)"
      @reset-zoom="onResetZoom($event)"
      :viewSetting="viewSettingRef"
      @view-setting="onViewSettingChange($event)"
      :style="{display:closeTools?'none':'block'}"

    />
    <div class="ui-zhrtc-body">
      <div
        class="ui-zhrtc-vis"
        ref="containerRef"
        :style="{ right: show ? '480px' : '20px' }"
      ></div>
      <!-- <div class="ui-zhrtc-runtime"> 参数区建设中... </div> -->
      <div class="ui-zhrtc-runtime" :style="{ width: show ? '480px' : '20px' }">
        <div
          :style="{ width: show ? '480px' : '20px' }"
          style="display: flex; position: relative; height: 100%; overflow: hidden"
        >
          <div style="height: 100%; width: 15px">
            <div class="triangle" @click="changeShow" v-if="show"></div>
            <div class="triangles" @click="changeShow" v-if="!show"></div>
          </div>
          <div
            style="
              display: flex;
              flex-wrap: wrap;
              border-left: 1px solid #333;
              margin-left: 20px;
              height: 100%;
              overflow: auto;
              transition: all 5s ease;
            "
            class="right"
          >
            <div
              v-for="(item, index) in listData"
              :key="index"
              style="
                display: flex;
                width: 50%;
                height: 50px;
                line-height: 50px;
                border-bottom: 1px solid #333;
              "
            >
              <div style="width: 50%; background: #fff; text-align: center">{{
                getName(item)
              }}</div>
              <div style="width: 50%; color: blue; text-align: center">{{ getValue(index) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { DataType, formatter, WellLogModel, WellLogRenderer } from 'well-log-vis'
import { bind } from 'neurons'
import RTCurveToolbar from '../toolbar.vue'
import { welllog } from './test/test-welllog'
import { IBindingRef } from 'neurons/binding/common/interfaces'
import { IWhereCondition } from 'well-log-vis/service/api'
import { IDataSet, ITable } from 'well-log-vis/model/interfaces'
import { testDataSet, testTable } from './test/test-table'
import { RtMaintainApi } from '@/api/base/rtmaintain'
import { IPlottingScale, IWellLogSetting } from 'well-log-vis/entity/welllog'

const { t } = useI18n()
const containerRef = ref<ElRef<HTMLElement>>()
const defaultScale = {
  // 时间比例尺（1cm:m）：每一厘米多少分钟
  timeScale: 3,
  // 时间刻度（分钟）：每个刻度多少分钟
  timeInterval: 10,
  // 距离比例尺(1mm:?)：每一毫米多少物理距离
  distanceScale: 500,
  // 距离刻度(?) - 每个刻度多少物理距离，该单位不确定，应与距离字段单位相同
  distanceInterval: 15000
}
const scaleSettingRef = ref<IPlottingScale>(defaultScale)
const defaultViewSetting = {
  fitWindow: false,
  autoRefresh: false,
  mouseCrosshair: true,
  mouseTooltip: true,
  showHeader: false,
  autoScrolling: false
}
const viewSettingRef = ref(defaultViewSetting)

let wellLogRef: IBindingRef<any>
let wellLogModel: WellLogModel
let defaultWellLogScale: IPlottingScale

onMounted(async () => {
  const data = await RtMaintainApi.getChildByCodeNew('ALS-23')
  list.value = data
  const container = unref(containerRef) as HTMLElement
  const model = (wellLogModel = WellLogModel.create(welllog))
  scaleSettingRef.value = model.get('settings.plottingScale') || defaultScale
  const modelSetting: IWellLogSetting = model.get('settings')
  viewSettingRef.value = {
    fitWindow: !!modelSetting.fitWindow,
    autoRefresh: !!modelSetting['autoRefresh'],
    mouseCrosshair: !modelSetting.hideMouseCrosshair,
    mouseTooltip: !modelSetting.hideMouseTooltip,
    showHeader: !!modelSetting['showHeader'],
    autoScrolling: !!modelSetting['autoScrolling']
  }
  defaultWellLogScale = { ...scaleSettingRef.value }
  wellLogRef = bind(
    `
    <ne-wlr [wellLog]="wellLog" [api]="api"></ne-wlr>
  `,
    {
      container: container,
      state: {
        wellLog: model,
        api: {
          table: {
            fetch: (id: any): Promise<ITable | null> => {
              if (testTable.id == id) return Promise.resolve(testTable)
              return Promise.resolve(null)
            },
            query: (
              tableId,
              columns: String[],
              wheres: IWhereCondition[]
            ): Promise<IDataSet | null> => {
              if (testTable.id == tableId) {
                return RtMaintainApi.getChildByCreateTime(welllog.id, new Date(0), new Date()).then(
                  (result) => {
                    // 1. 需要完整的日期类型
                    result = (result || []).map((obj) => {
                      // 调整p1 p2的数据类型
                      const p1 = obj.p1.split('-')
                      const p2 = obj.p2.split(':')
                      const date = new Date(
                        parseInt(p1[0]),
                        parseInt(p1[1]) - 1,
                        parseInt(p1[2]),
                        parseInt(p2[0]),
                        parseInt(p2[1]),
                        parseInt(p2[2])
                      )
                      // console.log(obj.p1 + ' ' + obj.p2, formatter.dateFormat(date, {format: 'yyyy-MM-dd hh:mm:ss'}));
                      obj.p1 = obj.p2 = date
                      return obj
                    })
                    // 2. 结果集应按日期正序排好序
                    result = result.sort((a, b) => {
                      return a.p1.getTime() - b.p1.getTime()
                    })
                    // 3. 修正结果数据类型问题
                    const values = (result || []).map((obj) => {
                      return testTable.columns.map((col) => {
                        if (col.dataType === DataType.INTEGER) {
                          return parseInt(obj[col.columnName])
                        } else if (col.dataType === DataType.DOUBLE) {
                          return parseFloat(obj[col.columnName])
                        } else {
                          return obj[col.columnName]
                        }
                      })
                    })
                    return Promise.resolve({
                      columns: testTable.columns,
                      values: values
                    })
                  }
                )
                // return Promise.resolve(testDataSet);
              }
              return Promise.resolve(null)
            }
          }
        }
      },
      requirements: [WellLogRenderer]
    }
  )
})

onUnmounted(() => {
  wellLogRef && wellLogRef.destroy()
})
const getName = (itemName) => {
  return t('list.' + itemName)
}
const getValue = (index) => {
  console.log(index, list.value.length, list.value[index])
  if (list.value.length === 0) {
    return ''
  } else {
    return list.value[index].value
  }
}
const list = ref([])
const listData = ref([
  'p1',
  'p2',
  'p3',
  'p4',
  'p5',
  'p6',
  'p7',
  'p8',
  'p9',
  'p10',
  'p11',
  'p12',
  'p13',
  'p14',
  'p15',
  'p16',
  'p17',
  'p18',
  'p19',
  'p20',
  'p21',
  'p22',
  'p23',
  'p24',
  'p25',
  'p26',
  'p27',
  'p28',
  'p29',
  'p30',
  'p31',
  'p32',
  'p33',
  'p34',
  'p35',
  'p36',
  'p37',
  'p38',
  'p39',
  'p40',
  'p41',
  'p42',
  'p43',
  'p44',
  'p45',
  'p46',
  'p47',
  'p48',
  'p49',
  'p50',
  'p51',
  'p52',
  'p53',
  'p54',
  'p55',
  'p56',
  'p57',
  'p58',
  'p59',
  'p60',
  'p61',
  'p62',
  'p63',
  'p64',
  'p65',
  'p66',
  'p67',
  'p68',
  'p69',
  'p70',
  'p71',
  'p72',
  'p73',
  'p74',
  'p75',
  'p76',
  'p77',
  'p78',
  'p79',
  'p80',
  'p81',
  'p82',
  'p83',
  'p84',
  'p85',
  'p86',
  'p87',
  'p88',
  'p89',
  'p90',
  'p91',
  'p92',
  'p93',
  'p94',
  'p95',
  'p96',
  'p97',
  'p98',
  'p99',
  'p100',
  'p101',
  'p102',
  'p103',
  'p104',
  'p105',
  'p106',
  'p107',
  'p108',
  'p109',
  'p110',
  'p111',
  'p112',
  'p113',
  'p114',
  'p115',
  'p116',
  'p117',
  'p118',
  'p119',
  'p120'
])
const show = ref(true)
const changeShow = () => {
  show.value = !show.value
  console.log(show.value, '===============')
}

const onScaleChange = (event) => {
  if (!wellLogModel) return
  scaleSettingRef.value = event.value
  wellLogModel.set('settings.plottingScale', { ...event.value })
}
const onShowParamsChange = (event) => {
  show.value = event.value
}
const onExport = (event) => {
  if (!wellLogModel) return
  console.log(wellLogModel.wellLog)
}
const onResetZoom = (event) => {
  if (!wellLogModel) return
  scaleSettingRef.value = { ...defaultWellLogScale }
  wellLogModel.set('settings.plottingScale', { ...defaultWellLogScale })
}
const onViewSettingChange = (event) => {
  if (!wellLogModel) return
  const setting = event.value
  viewSettingRef.value = setting
  wellLogModel.set('settings.fitWindow', setting.fitWindow)
  wellLogModel.set('settings.autoRefresh', setting.autoRefresh)
  wellLogModel.set('settings.hideMouseCrosshair', !setting.mouseCrosshair)
  wellLogModel.set('settings.hideMouseTooltip', !setting.mouseTooltip)
  wellLogModel.set('settings.showHeader', setting.showHeader)
  wellLogModel.set('settings.autoScrolling', setting.autoScrolling)
}
const closeTools = ref(false)
const closeTool = () => {
  closeTools.value = !closeTools.value
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

.ui-zhrtc-page * {
  box-sizing: border-box;
}

.ui-zhrtc-page {
  position: absolute;
  top: 40px;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 92px 0 0px 0px;
  .ui-zhrtc-toolbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    border-bottom: solid 1px $blackLight;
  }
  .ui-zhrtc-body {
    position: relative;
    width: 100%;
    height: 100%;
    .ui-zhrtc-vis {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      right: 480px;
      transition: transitionNormal(right);
      .ne-wlr {
        position: relative;
        width: 100%;
        height: 100%;
        .ne-wlr-tracks {
          position: relative;
          width: 100%;
          height: 100%;
          overflow: auto;
          white-space: nowrap;
          & > .ne-wltr {
            white-space: initial;
          }
        }
      }
    }
    .ui-zhrtc-runtime {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      width: 480px;
      transition: transitionNormal(width);
    }
  }
}
.card {
  display: flex;
  height: 300px;
  flex: 1;
  font-weight: bold;
  background: #ffffe1;
}
.line {
  height: 100px;
  text-align: center;
  line-height: 50px;
}
.fouLine {
  height: 75px;
  text-align: center;
  line-height: 37px;
}
.seLine {
  border: 2px solid #333;
  border-left: none;
  padding: 100px 0px;
  text-align: center;
  line-height: 25px;
  width: 20%;
}
.thiLine {
  border: 2px solid #333;
  border-left: none;
  width: 20%;
}
.echart {
  height: 500px;
  width: 100%;
  display: flex;
}
.list {
  width: 20%;
  height: 100%;
  border: 2px solid #333;
  border-top: none;
}
.lists {
  width: 20%;
  height: 100%;
  border: 2px solid #333;
  border-top: none;
  border-left: none;
}
#Echarts {
  height: 100%;
  width: 100%;
}
.triangle {
  position: absolute;
  left: 0;
  top: 50%;
  margin: auto;
  width: 0;
  height: 0;
  border-bottom: 10px solid transparent;
  border-right: 20px solid #dedede;
  border-top: 10px solid transparent;
}
.triangles {
  position: absolute;
  left: 0;
  top: 50%;
  margin: auto;
  width: 0;
  height: 0;
  border-bottom: 10px solid transparent;
  border-left: 20px solid #dedede;
  border-top: 10px solid transparent;
}
// ::-webkit-scrollbar {
//   display: none; /* Chrome, Safari, Opera*/
// }
.ui-zhrtc-toolbar-right {
  position: absolute;
  right: 0px;
  top: 0px;
  z-index:999
}
</style>
